package com.myapp.struts.menu;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import javax.servlet.ServletContext;

public class JavaToText extends MenuFormat {

    File f;
    private static JavaToText txt;

    public JavaToText getInstance() {
        if (txt == null) {
            txt = new JavaToText();
            return txt;
        } else {
            return txt;
        }
    }
    //arraylist of fooditems

    public String formatText(ArrayList<FoodItems> foodItem, String outFile) throws Exception {
        f = new File(outFile, "Menu_Text.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("\t\t MENU \n\n");
        printHTML(foodItem, bw, Constants.BREAKFAST);
        printHTML(foodItem, bw, Constants.SNACK);
        printHTML(foodItem, bw, Constants.APPETIZER);
        printHTML(foodItem, bw, Constants.LUNCH);
        printHTML(foodItem, bw, Constants.DINNER_FOOD);
        printHTML(foodItem, bw, Constants.DESSERT);
        printHTML(foodItem, bw, Constants.SIDE_DISH);

        bw.close();

        System.out.println("file path" + f.getAbsolutePath());
        return f.getAbsolutePath();

    }

    private void printHTML(ArrayList<FoodItems> foodItem, BufferedWriter bw, String type)
            throws IOException {
        Boolean head = false;
        for (FoodItems foodItems : foodItem) {

            if (foodItems.getCategory().equals(type)) {
                if (head == false) {
                    bw.write("\n" + type);
                    head = true;
                }
                bw.write("\n\n");

                String price;
                if (foodItems.getCountry().equals(Constants.GREAT_BRITAN)) {
                    price = "GBP " + foodItems.getPrice();
                } else {
                    price = "$ " + foodItems.getPrice();
                }

                String formatStr = "%-50s %-100s";
                bw.write(String.format(formatStr, foodItems.getName(), price));
                bw.write("\n");
                bw.write(foodItems.getDescription());
                bw.write("\n\n");

            }

        }
    }

    public File getF() {
        return f;
    }

    public void setF(File f) {
        this.f = f;
    }
}
